package com.example.demo.mytest;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ReadFile {
    /**
     * 递归查找某个文件夹下的文件数目
     * @param path
     * @param fileList
     * @return
     */
    public static List<File> readFileList(String path, List<File> fileList) {
        File file = new File(path);
        File[] files = file.listFiles();
        if (null == files) {
            //如果文件是空，直接退出
            return null;
        }
        for (File f : files) {
            //是否是文件还是文件夹
            if (f.isFile()) {
                fileList.add(f);
            } else if (f.isDirectory()) {
                readFileList(f.getAbsolutePath(),fileList);
            }
        }
        return fileList;
    }

    public  List<File> readFileListByThread(String path) {
        List<File> fileList=new ArrayList<>();
        File file = new File(path);
        File[] files = file.listFiles();
        if (null == files) {
            //如果文件是空，直接退出
            return null;
        }
        ExecutorService executorService=Executors.newFixedThreadPool(8);
        readFileCallable callable=new readFileCallable(path);
        FutureTask futureTask=new FutureTask(callable);
        executorService.submit(futureTask);
        try {
            fileList = (List<File>) futureTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return fileList;
    }

    /**
     * 多线程读取文件夹下文件的数量
     */
    class  readFileCallable implements Callable {
        String path;
        readFileCallable(String path){
            this.path=path;
        }
        @Override
        public List<File> call() throws Exception {
            List<File> fileList=new ArrayList<>();
            File file = new File(path);
            File[] files = file.listFiles();
            if (null == files) {
                //如果文件是空，直接退出
                return null;
            }
            for (File f : files) {
                //是否是文件还是文件夹
                if (f.isFile()) {
                    fileList.add(f);
                } else if (f.isDirectory()) {
                    readFileList(f.getAbsolutePath(),fileList);
                }
            }
            return fileList;
        }
    }
}
